package org.su.webadapter.bind;

import org.su.generalmvc.IEditor;
import org.su.generalmvc.util.ObjectUtils;
import org.apache.commons.lang.StringUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.lang.reflect.Array;
import java.lang.reflect.Method;

/**
 * 数组编辑器，将传入的字符串数组，转换为对应类型的数组
 * @author yangchuan
 * @CreateTime 2010-7-29 下午03:03:43
 *
 * @param <T>
 */
public  class ArrayParamEditor<T> implements IEditor {
	private AbstractParameterEditor editor;
	private Class<T> clazz;
	
	public ArrayParamEditor(Class<T> clazz,IEditor editor) {
		this.editor = (AbstractParameterEditor)editor;
		this.clazz = clazz;
	}

	@Override
	public Object getParamValue(String paramName, Class<?> paramType, int paramIndex, Method writer, ServletRequest request,
								ServletResponse response) {
		return parseText(request.getParameterValues(paramName));
	}

	
	
	@SuppressWarnings("unchecked")
	public T[] parseText(String[] text){
		T[] result = null;
		if(text == null) return null;
		if(text.length==1 && StringUtils.isBlank(text[0])){
		  return null;
		}
		if(!ObjectUtils.isEmpty(text)){
			result = (T[]) Array.newInstance(this.clazz, text.length);
			for(int i=0;i<result.length;i++){
				result[i] =  (T) editor.parseText(text[i]);
			}
		}
		return result;
	}
}
